/*
 * @Description: 全宗表格组件
 * @Author: Rfan
 * @Date: 2022-01-07 15:20:55
 * @LastEditTime: 2022-05-26 17:58:23
 */

import { useMemo, useState } from 'react';
import { Button, Space, Table, Tag } from 'antd';
import { useNavigate } from 'react-router-dom';
import { useUnitContext } from '../contexts/UnitContext';
import { arrToTree, formatDate } from '@/utils';
import { useFormatMessage } from '@/utils/intlHelpers';
import AddUnitDialog from './dialogs/AddUnitDialog';
import EditUnitDialog from './dialogs/EditUnitDialog';
import type { IUnit } from '@/interfaces/unit';

const { Column } = Table;

const List = () => {
  const formatMessage = useFormatMessage();
  const navigate = useNavigate();
  const {
    listType,
    list,
    loading,
    total,
    listQuery,
    setListQuery,
    selectItems,
    setSelectedItem,
    stateFilter
  } = useUnitContext();

  // 选中的单位
  const [selectUnit, setSelectUnit] = useState<IUnit | {}>({});
  // 编辑弹窗显示状态
  const [unitDialogVisible, setUnitDialogVisible] = useState(false);
  // 编辑弹窗显示状态
  const [addSubDialogVisible, setAddSubDialogVisible] = useState(false);

  // 切换页码触发
  const pageChange = (page: number, pageSize: number) => {
    setListQuery([{ key: 'pageNo', value: page }]);
  };

  // 表格选项相关设置
  const onSelectChange = (selectedRowKeys: number[]) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    setSelectedItem(selectedRowKeys);
  };

  const rowSelection = {
    selectItems,
    onChange: onSelectChange
  };

  const showEditModal = (data: IUnit) => {
    setSelectUnit(data);
    setUnitDialogVisible(true);
  };

  /**
   * @description: 打开新建子单位弹窗
   * @param {IUnit} data 选中单位
   */
  const showModal = (data: IUnit) => {
    setSelectUnit(data);
    setAddSubDialogVisible(true);
  };

  const jumpToFond = (unitId: number): void => {
    navigate(`../fonds?unitId=${unitId}`);
  };

  return (
    <>
      <Table
        dataSource={listType === 1 ? arrToTree(list) : list}
        loading={loading}
        rowKey="id"
        rowSelection={rowSelection}
        pagination={{
          current: listQuery.pageNo,
          pageSize: listQuery.pageSize,
          total,
          onChange: pageChange
        }}
        scroll={{
          x: 'max-content'
        }}
        bordered
      >
        <Column title="ID" dataIndex="id" key="id" align="center" width={100} />
        <Column title="单位编码" dataIndex="unitCode" key="unitCode" align="center" />
        <Column title="单位名称" dataIndex="unitName" key="unitName" align="center" />
        <Column
          title="状态"
          dataIndex="isValid"
          key="isValid"
          align="center"
          render={(isValid) => <Tag color="blue">{stateFilter(isValid)}</Tag>}
        />
        <Column
          title="创建时间"
          dataIndex="operateTime"
          key="operateTime"
          align="center"
          render={(text) => formatDate(text)}
        />
        <Column title="创建人" dataIndex="operatorName" key="operatorName" align="center" />
        <Column title="单位备注" dataIndex="remark" key="remark" align="center" />
        <Column
          title={formatMessage('tableAction')}
          key="action"
          align="center"
          render={(_text, record: any) => (
            <Space>
              <Button
                type="link"
                onClick={() => {
                  showModal(record);
                }}
              >
                添加子单位
              </Button>
              <Button
                type="link"
                onClick={() => {
                  showEditModal(record);
                }}
              >
                编辑
              </Button>
              <Button
                type="link"
                onClick={() => {
                  jumpToFond(record.id);
                }}
              >
                查看全宗
              </Button>
            </Space>
          )}
        />
      </Table>
      {useMemo(
        () => (
          <EditUnitDialog
            visible={unitDialogVisible}
            data={selectUnit}
            onClose={() => {
              setUnitDialogVisible(false);
            }}
          />
        ),
        [unitDialogVisible]
      )}
      {useMemo(
        () => (
          <AddUnitDialog
            visible={addSubDialogVisible}
            data={{ pid: 'pid' in selectUnit ? selectUnit.id : undefined }}
            onClose={() => {
              setAddSubDialogVisible(false);
            }}
          />
        ),
        [addSubDialogVisible]
      )}
    </>
  );
};

export default List;
